package com.lagou.cl.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 程  林
 * @date 2020-06-02 23:28
 * @description //
 * @since V1.0.0
 */
@Configuration
public class ZkConfig {

	@Autowired
	private ZooKeeperProperties zkProperties;

	@Bean
	public CuratorFramework curatorFramework() {

		StringBuilder sb = new StringBuilder();
		StringBuilder zkAddr = sb.append(zkProperties.getZkHost()).append(":").append(zkProperties.getPort());

		/**
		 * 重试之间等待的初始时间
		 * 重试的最大次数
		 */
		RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);

		//fluent编程风格
		CuratorFramework client = CuratorFrameworkFactory.builder()
				.connectString(zkAddr.toString())
				//会话超时时间
				.sessionTimeoutMs(5000)
				//连接超时时间
				.connectionTimeoutMs(3000)
				//重试策略
				.retryPolicy(retryPolicy)
				//命名空间
				.namespace(Constant.NAMESPACE)
				.build();
		return client;
	}
}
